package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.dao.QxMapMapper;
import com.xxl.job.executor.model.QxMap;
import com.xxl.job.executor.utils.CmUtil;
import com.xxl.job.executor.utils.ConstUtil;
import com.xxl.job.executor.utils.TusFileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;

import java.net.URL;

/*
    "全国气象雷达图数据抓取"

 */


@Component
public class RadarImageForChinaAllTask {
    private static Logger logger = LoggerFactory.getLogger(RadarImageForChinaAllTask.class);

    private String taskContents;
    @Autowired
    private ConstUtil constUtil;
    @Autowired
    private QxMapMapper qxMapMapper;

    @XxlJob(value = "RadarImageForChinaAllTask",init = "init", destroy = "destroy")
    public ReturnT<String> RadarImageForChinaAllTask(String param) throws Exception {
        String imgUrl = "";
        String dataTime = "";
        String time = "";
        String mediumImgUrl = "";
        // 获取html文本内容
        Document doc = getHtml(constUtil);

        Element img = doc.select("[id=\"imgpath\"]").first();

        mediumImgUrl = img.attr("src");

        dataTime = img.attr("data-time");

        time = mediumImgUrl.substring(mediumImgUrl.lastIndexOf("_") + 1, mediumImgUrl.lastIndexOf("_") + 9) + dataTime.substring(dataTime.lastIndexOf(" "));

        this.taskContents = "imgUrl=" + mediumImgUrl + "______time=" + time;
        // 下载图片
        Download(mediumImgUrl, time);
        System.out.println("1111111111111111111111111");

        return ReturnT.SUCCESS;
    }
    public static Document getHtml(ConstUtil constUtil) {
        Document doc = null;
        try {
//            if (constUtil.useProxy) {
//                // 设置代理
//                Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(constUtil.proxyId, constUtil.proxyPort));
//                doc = Jsoup.connect(constUtil.chinaAllUrl)
//                        .proxy(proxy)
//                        .userAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)")
//                        .timeout(999999999)
//                        .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
//                        .header("Accept-Encoding", "gzip, deflate")
//                        .header("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
//                        .header("Connection", "keep-alive")
//                        //是忽略请求类型
//                        .ignoreContentType(true)
//                        .get();
//            } else {
                doc = Jsoup.connect(constUtil.chinaAllUrl)
                        .userAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)")
                        .timeout(999999999)
                        .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                        .header("Accept-Encoding", "gzip, deflate")
                        .header("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
                        .header("Connection", "keep-alive")
                        //是忽略请求类型
                        .ignoreContentType(true)
                        .get();
//            }
        } catch (Exception e) {
            logger.error("设置代理", e);
            e.printStackTrace();
        }
        return doc;
    }

    /**
     * 下载图片
     *
     * @param imgUrl
     * @param time
     */
    private void Download(String imgUrl, String time) {
        QxMap qxMap;
        HttpURLConnection connection;
        if (imgUrl.length() > 0 && time.length() > 0) {
           // qxMapMapper = SpringContextHolder.getBean(QxMapMapper.class);
            // 根据时间和图像类型判断当前图片是否已下载
            String type = 2 + "";
           // qxMap = qxMapMapper.selectByTime(time, type);
           // if (qxMap == null) {
                InputStream in = null;
                FileOutputStream fo = null;
                try {
                    String imageName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
                    imageName = imageName.substring(0, imageName.lastIndexOf("?"));
                    URL uri = new URL(imgUrl);
//                    if (constUtil.useProxy) {
//                        // 设置代理
//                        Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(constUtil.proxyId, constUtil.proxyPort));
//                        connection = (HttpURLConnection) uri.openConnection(proxy);
//                    } else {
                        connection = (HttpURLConnection) uri.openConnection();
//                    }
//                  //  图片存储服务器tus
                    String filePath = TusFileUtils.fileUpload(connection, constUtil.tusdUrl);

                    //图片存储本地
                    in = connection.getInputStream();
                    String nowTime = CmUtil.date2day(null);
//                    File f = new File(constUtil.realUrl2 + "/" + nowTime);
//                    if (!f.exists() && !f.isDirectory()) {
//                        f.mkdirs();
//                    }
//                    String path = constUtil.realUrl2 + "/" + nowTime + "/" + imageName;
//                    fo = new FileOutputStream(new File(path));
//                    byte[] buf = new byte[1024];
//                    int length = 0;
//                    while ((length = in.read(buf, 0, buf.length)) != -1) {
//                        fo.write(buf, 0, length);
//                    }
                    //写入数据库
                    qxMap = new QxMap();
                    qxMap.setId(CmUtil.getUUID());
                    qxMap.setCreatetime(CmUtil.date2db(null));
                    qxMap.setType("2");
                    qxMap.setFilename(imageName);
                    qxMap.setFilepath(filePath);
                  //  qxMap.setFilepath(path);
                    qxMap.setPublishtime(time);
                    qxMapMapper.insert(qxMap);
                    this.taskContents = "下载完成：imgUrl=" + imgUrl + "______time=" + time;
                } catch (Exception e) {
                    e.printStackTrace();
                    this.taskContents = "下载异常：imgUrl=" + imgUrl + "______time=" + time;
                } finally {
                    try {
                        if (fo != null) {
                            fo.flush();
                            fo.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        if (in != null) {
                            in.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
//    }


    public void init(){
        logger.info("init");
    }
    public void destroy(){
        logger.info("destory");
    }

}
